package com.ms.p2p.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.bean.Message;


import com.ms.common.exception.NoticeException;
import com.ms.p2p.controller.BaseController;
import com.ms.p2p.entity.FuyouBank;
import com.ms.p2p.entity.member.Auth;
import com.ms.p2p.plugin.IPlugin;
import com.ms.common.utils.AppContext;
import com.ms.common.utils.MsDateUtils;
import com.ms.p2p.provider.*;
import com.ms.p2p.plugin.validation.annotation.*;
import com.ms.p2p.Constants;
import com.ms.p2p.bean.PageBean;

import com.ms.p2p.entity.account.Account;
import com.ms.p2p.entity.account.AccountBank;
import com.ms.p2p.entity.account.AccountRecharge;
import com.ms.p2p.entity.account.Withdraw;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.entity.system.PayMethod;
import com.ms.p2p.plugin.payment.IPaymentEvent;
import com.ms.p2p.plugin.payment.PaymentPluginBundle;
import com.ms.p2p.utils.TradeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping({ "/member/account" })
public class MemberAccountController extends BaseController {
	@Autowired
	PaymentPluginBundle paymentPluginBundle;

	@Reference
	private MemberAccountProvider account_Service;
	@Reference
	private MemberAccountBankProvider bankService;
	@Reference
	private MemberWithDrawProvider memberWithDrawProvider;
	@Reference
	private MemberAccountRechargeProvider rechargeService;
	@Reference
	private MemberAccountRecordProvider logService;
	@Reference
	private SettingProvider settingProvider;
	@Reference
	private MemberAccountProvider memberAccountProvider;
	@Reference
	private PayMethodProvider payMethodProvider;
	@Reference
	private MemberAccountBankProvider memberAccountBankProvider;

	@Reference
	private FuyouProvider fuyouProvider;

	@Reference
	private CertiFiCationProvider certiFiCationProvider;
	/**
	 * 收支明细
	 */
	@RequestMapping({ "/log" })
	public String cashdata(String logType, String beginDate, String endDate, String currentPage,Model model){
		PageBean page = new PageBean();
		if (StringUtils.isNotBlank(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		Member user = getCurrentUser();
		List<Map<String, Object>> logs =
				logService.findPager(user.getId() + "", null, logType, beginDate, endDate, page.getBegin(),
						page.getPageSize());

		page.setTotalCount(logService.findCount(user.getId() + "", null,logType, beginDate, endDate));
		// 累计收入
		Map<String, Object> totalIn = logService.staticMoney("in", user.getId() + "");
		// 累计支出
		Map<String, Object> totalOut = logService.staticMoney("out",user.getId() + "");
		model.addAttribute("logs", logs);
		model.addAttribute("page", page);
		model.addAttribute("totalIn", totalIn);
		model.addAttribute("totalOut", totalOut);
		// 搜索条件、
		model.addAttribute("beginDate", beginDate);
		model.addAttribute("endDate", endDate);
		model.addAttribute("logType", logType);
		return "/customer/member/account/log/list";
	}
	@RequestMapping({ "/go_recharge_online" })
	public  String onlineRecharge(Model model) {

		List list = payMethodProvider.findOnline();
		Account account  = account_Service.findByUserId(getCurrentUser().getId());
		model.addAttribute("account", account);
		model.addAttribute("list", list);
		List<FuyouBank> banks = fuyouProvider.getList();
		model.addAttribute("banks",banks);

		return "/customer/member/account/rechargecash/recharge_online";
	}
	@RequestMapping( { "/onlinesubmit" })
	public  String onlinesubmit(String money, String payid, HttpServletRequest request) throws Exception {
		Member user = getCurrentUser();
		List<IPlugin> plugins = paymentPluginBundle.getPluginList();
		HashMap map = new HashMap();
		for (IPlugin plugin : plugins) {
			if (payid.equals(plugin.getId())) {
				IPaymentEvent pay = (IPaymentEvent) plugin;
				if("54".equals(plugin.getId())){
					map.put("bank_code",getRequest().getParameter("bankcode"));

				}
				if("56".equals(plugin.getId())){
					Auth auth = certiFiCationProvider.findByUserId(user.getId());
					AccountBank bank = memberAccountBankProvider.findByUserId(user.getId());
					if(auth==null)
						throw new NoticeException("请先实名认证");
					if(bank==null)
						throw new NoticeException("请先绑定银行卡");

					map.put("realname",auth.getReal_name());
					map.put("id_card_no",auth.getId_number());
					map.put("bank_cardno",bank.getBank_cardno());

				}
				String url =  pay.onPay(user.getId(),new BigDecimal(money),map,request);
				System.out.print(url);
				return url;
			}
		}
		return null;
	}
	/**
	 * 提交提现申请
	 */
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "money", message = "提现金额不能为空"),
			@RequiredStringValidator(fieldName = "captcha", message = "图形验证码不能为空")

	},token = {
			@TokenValidator
	}
	)
	@RequestMapping("/docash")
	@ResponseBody
	public Message submit(Double money, String captcha) throws Exception {
		//验证码校验
		String sessionCaptcha = (String) AppContext.getSessionAttr(Constants.CAPTCHA_SESSION_KEY);
		if (StringUtils.isBlank(sessionCaptcha) || StringUtils.isBlank(captcha) || !sessionCaptcha.toLowerCase().equals(captcha.toLowerCase())) {
			return Message.error("图形验证码不能为空");
		}
		Member user = getCurrentUser();
		Account account = memberAccountProvider.findByUserId(user.getId());
		AccountBank banCard = bankService.findByUserId(user.getId());
		if (banCard == null) {
			return Message.error("请先绑定您的银行卡!") ;
		}
		if (banCard.getStatus() == 0) {
			return Message.error("为了防止恶意提现,请先使用该银行卡充值，才能提现!");
		}
		if (money < 100 || money > 50000) {
			return Message.error("单笔提现金额为100-50000元");
		}

		if (BigDecimal.valueOf(money).compareTo(account.getBalance()) > 0) {
			return Message.error("提现金额大于账户最大可用余额，请重新操作!");
		}
		Withdraw widthdraw = new Withdraw();
		widthdraw.setUser_id(user.getId());
		widthdraw.setTrade_no(TradeUtil.getTrano()+"");
		widthdraw.setTotal(new BigDecimal(money));
		widthdraw.setAddtime(MsDateUtils.getTime());
		widthdraw.setAddip(AppContext.getRemoteIp());
		widthdraw.setCrad_no(banCard.getBank_cardno());
		widthdraw.setBank(banCard.getBank());
		widthdraw.setBranch(banCard.getBranch());
		memberWithDrawProvider.withDrawApply(widthdraw, AppContext.getRemoteIp());
		AppContext.removeAttribute(Constants.CAPTCHA_SESSION_KEY);
		return successMessage;
	}
	@RequestMapping({ "/withdrawals" })
	public String withdrawals(String type, String currentPage, Model model) {
		Member user = getCurrentUser();

			Account account = account_Service.findByUserId(user.getId());
			model.addAttribute("account", account);
			PageBean page = new PageBean();
			if (currentPage != null && !("".equals(currentPage))) {
				page.setCurrentPage(Integer.parseInt(currentPage));
			}

				List<Map<String, Object>> cashRecords = memberWithDrawProvider.findPager(null,
						user.getId() + "", null, null, null, page);

				page.setTotalCount(memberWithDrawProvider.findCount(null, user.getId() + "", null,
						null, null));
				model.addAttribute("cashRecords", cashRecords);



		model.addAttribute("page", page);
		model.addAttribute("type", type);
		return "/customer/member/account/rechargecash/withdrawals";
	}
	@RequestMapping({ "/recharges" })
	public String prepaidCashRecords(String type, String currentPage, Model model) {
		Member user = getCurrentUser();

			Account account = account_Service.findByUserId(user.getId());
			model.addAttribute("account", account);
			PageBean page = new PageBean();
			if (currentPage != null && !("".equals(currentPage))) {
				page.setCurrentPage(Integer.parseInt(currentPage));
			}

				List<AccountRecharge> rechargeRecords = rechargeService
						.findPager(user.getId(), page.getBegin(),
								page.getPageSize());
				page.setTotalCount(rechargeService.findCount(user.getId()));
				model.addAttribute("rechargeRecords", rechargeRecords);

			model.addAttribute("page", page);


		return "/customer/member/account/rechargecash/recharges";
	}
	/**
	 * 到充值页面
	 */
	@RequestMapping({ "/go_recharge_offline" })
	public String toRecharge(Model model) {
		Member user = getCurrentUser();
		Account account = memberAccountProvider.findByUserId(user.getId());
		// 支付方式
		List<PayMethod> payments = payMethodProvider.find(1);
		model.addAttribute("payments", payments);
		model.addAttribute("account", account);
		return "/customer/member/account/rechargecash/recharge";

	}
	@RequestMapping({ "/gocash" })
	public String toCash(Model model)
			throws Exception {
		Member user = getCurrentUser();
		AccountBank bank = memberAccountBankProvider.findByUserId(user.getId());
		if(bank==null){
			throw new NoticeException("请先绑定银行卡");

		}
		model.addAttribute("account", memberAccountProvider.findByUserId(user.getId()));
		model.addAttribute("bank", memberAccountBankProvider.findByUserId(user.getId()));
		model.addAttribute("integral", null);
		String deduct_integral = settingProvider.findValueByCode("deduct_integral");
		model.addAttribute("deduct_integral",Integer.parseInt(deduct_integral));
		return "/customer/member/account/rechargecash/cash";
	}

	/**
	 * 到银行卡设置页面
	 * @param session
	 * @return
	 */
	@RequestMapping({ "/edit" })
	public String toBankCardSet( HttpSession session, Model model) {
		Member user = (Member) session.getAttribute("loginUser");
		AccountBank bankCard = bankService.findByUserId(user.getId());
		model.addAttribute("bankCard", bankCard);
		return "/customer/member/account/bank/edit";
	}


	@RequestMapping({ "/bankinfo" })
	public String toAddBank(HttpSession session, Model model) {
		Member user = (Member) session.getAttribute("loginUser");
		AccountBank bankCard = bankService.findByUserId(user.getId());
		model.addAttribute("bankCard", bankCard);
		return "/customer/member/account/bank/info";
	}



}
